package com.web709.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.web709.entity.Activity;
import com.web709.entity.ActivityParticipant;
import com.web709.mapper.ActivityMapper;
import com.web709.service.ActivityParticipantService;
import com.web709.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {
    @Autowired
    private ActivityParticipantService participantService;

    @Override
    public List<Activity> listByPage(Integer page, Integer size) {
        // 参数校验
        if (page < 1) page = 1;
        if (size < 1 || size > 100) size = 10;

        // 构建分页参数（MyBatis-Plus页码从1开始）
        Page<Activity> pageParam = new Page<>(page, size);

        // 构建查询条件：按创建时间倒序 + 只查询有效活动
        LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Activity::getCreateTime); // 假设有状态字段

        // 执行分页查询
        Page<Activity> result = baseMapper.selectPage(pageParam, queryWrapper);

        // 关联查询参与人数


        return result.getRecords();
    }

    @Override
    public Activity getByIdWithParticipants(Integer id) {
        // 查询活动
        Activity activity = baseMapper.selectById(id);
        return activity;
    }

    @Override
    public List<Activity> listByUserId(Integer userId) {
        // 查询用户参与的活动
        List<Activity> activities = participantService.list(new LambdaQueryWrapper<ActivityParticipant>()
                .eq(ActivityParticipant::getUserId, userId)
                .select(ActivityParticipant::getActivityId)
        ).stream()
                .map(activityParticipant -> baseMapper.selectById(activityParticipant.getActivityId()))
                .collect(Collectors.toList());
        return activities;

    }

    @Override
    public List<Activity> listByUserIdV(Integer userId) {
        // 查询用户参与的活动
        List<Activity> activities = participantService.list(new LambdaQueryWrapper<ActivityParticipant>()
                        .eq(ActivityParticipant::getVolunteerId, userId)
                        .select(ActivityParticipant::getActivityId)
                ).stream()
                .map(activityParticipant -> baseMapper.selectById(activityParticipant.getActivityId()))
                .collect(Collectors.toList());
        return activities;
    }
}
